import os
from config import Config

class TV:

    def __init__(self):
        '''base class for launching tv from mplayer'''
        import time
        self._fifo = '/tmp/fifo%d' % time.time()
        self._scan = '/tmp/scan%d' % time.time()
        self._mplayer_cmd = 'mplayer -wid %s -slave -idle -noconsolecontrols -input file=%s'
        self._channel = 1 
        self.conf = Config()
    
    def quit(self):
        '''stop tv and delete fifo for mplayer'''
    
        self._execute('quit')
        self._player.close()
    
    def off(self):
        '''turn off the tv'''
        if hasattr(self, '_player'):
            self._execute('quit')
            self._player.close()            
            delattr(self, '_player')
    
        if os.path.exists(self._fifo):
            os.unlink(self._fifo)
        
        if os.path.exists(self._scan):
            os.unlink(self._scan)
    
    def on(self, video_area, command, scan=False):
        '''turn on the tv'''
        from subprocess import Popen, PIPE
        
        if os.path.exists(self._fifo):
            os.unlink(self._fifo)
        os.mkfifo(self._fifo)
        
        cmd = '%s %s -quiet' % (self._mplayer_cmd % (video_area.window.xid, self._fifo), command)
        if scan: # this is for tv scanning
            Popen(cmd.split(), stdout=open(self._scan, 'w+b'), stderr=PIPE)
            self._scanner = open(self._scan, 'r')
        else:
            Popen(('%s -msglevel all=-1' % cmd).split(), stdout=PIPE, stderr=PIPE)
        
        self._player = open(self._fifo, 'w')
        self._execute('play\n')
        
        w, h = self.conf.screen_size
        video_area.set_size_request(w, h)
        video_area.window.draw_rectangle(video_area.get_style().black_gc, True, 2, 2, w, h)
            
    def change_channel(self, value):
        '''Changing channel on previous/next channel button click'''
        c = self._channel + value
        if c > len(self.conf.channels[1]):
            c = 1
        elif c == 0:
            c = len(self.conf.channels[1])
        self._channel = c
        
        if hasattr(self, '_player'):
            self._execute('tv_set_channel %s' % c)
    
    def _execute(self, command):
        '''Executes a command and flush the buffer'''
        self._player.write('%s\n' % command)
        self._player.flush()
